package br.com.fogas.medicao.business;

import java.sql.SQLException;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.support.v4.app.Fragment;
import br.com.fogas.database.FogasDatabase;
import br.com.fogas.database.entidade.NotaFiscal;
import br.com.fogas.medicao.R;
import br.com.fogas.medicao.activity.PlanoLocalFragment;
import br.com.fogas.medicao.application.Constants;
import br.com.fogas.medicao.application.LoadFragment;
import br.com.fogas.notafiscal.NotaFiscalEngine;
import br.com.fogas.utils.dialog.DialogAlert;
import br.com.fogas.utils.task.ServiceTask;
import br.com.fogas.utils.task.ServiceTaskBusiness;

public class CancelarNotaBusiness implements ServiceTaskBusiness {
	
	private Fragment fragment;
	private FogasDatabase database;
	private NotaFiscal notaFiscal;

	public CancelarNotaBusiness(Fragment fragment, FogasDatabase database,
			NotaFiscal notaFiscal) {
		this.fragment = fragment;
		this.database = database;
		this.notaFiscal = notaFiscal;
	}

	@Override
	public void start(ServiceTask serviceTask) {
		try {
			NotaFiscalEngine.cancelarNota(database, notaFiscal);
			
			DialogAlert.newInstance()
			.setTitle(R.string.dialog_title_alert)
			.setMessage(R.string.dialog_cancelar_nota_sucesso)
			.setPositiveClick(direcionar)
			.showDialog(fragment.getActivity().getSupportFragmentManager());
		} catch (SQLException e) {
			DialogAlert.newInstance()
			.setTitle(R.string.dialog_title_alert)
			.setMessage(R.string.dialog_cancelar_nota_error)
			.setPositiveClick(direcionar)
			.showDialog(fragment.getActivity().getSupportFragmentManager());
		}
	}
	
	OnClickListener direcionar = new OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			LoadFragment loadFragment = new LoadFragment(fragment.getActivity().getSupportFragmentManager());
			loadFragment.initializeFragment(true, new PlanoLocalFragment(), Constants.FRAGMENT_PLANO_LOCAL);
		}
	};
}